CSS [attribute] Selector
The [attribute] Selector is used to select all the elements that have the specified attribute and applies the CSS property to that attribute. For example, the selector [class] will select all the elements with the style attribute.
Example 1: This example applies style to all elements with class attributes.
<!DOCTYPE html>
<html>
<head>
<title>Attributes selector</title>
<style>
[class] {
text-align: center;
Color: green;
}
.gfg {
font-size: 40px;
font-weight: bold;
margin-bottom: -20px;
}
</style>
</head>
<body>
<div class="gfg">w3wiki</div>
<p class="geeks">
A computer science portal for geeks
</p>
</body>
</html>
Output:
This selector can be used to restrict some particular elements, then it needs to specify that element before the attribute selector.
Example 2: This example apply CSS to the div with style attribute only
<!DOCTYPE html>
<html>
<head>
<title>Attribute selector</title>
<style>
div[style] {
text-align: center;
color: green;
font-size: 40px;
font-weight: bold;
margin-bottom: -20px;
}
p {
text-align: center;
font-size: 17px;
}
</style>
</head>
<body>
<div style="color:green">w3wiki</div>
<p>
A computer science portal for geeks
</p>
</body>
</html>
Output:
Multiple elements can be selected using the comma operator
h2, p[style] {
background-color: #00b93e;
}
CSS Attribute Selector
The CSS Attribute Selector is a very useful approach that targets elements based on their specific attributes or attribute values. This allows for precise styling of HTML elements that share common attributes, enhancing the consistency and efficiency of your CSS code. Lets see how to work with CSS Attribute Selector.
Syntax:
[attribute]{
/* Styles*/
}
// OR
element [attribute] {
/* Styles*/
}
// OR
[attribute ="value "]
{
/* Styles*/
}
There are several types of attribute selectors which are discussed below:
Contact Us